package me.shurufa.fragments;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.github.ybq.android.spinkit.SpinKitView;
import com.malinskiy.superrecyclerview.SuperRecyclerView;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.HttpRequest;
import me.shurufa.R;
import me.shurufa.adapter.NewCatalogAdapter;
import me.shurufa.bean.Catalog;
import me.shurufa.net.API;
import me.shurufa.net.RequestParams;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.CatalogListResp;
import me.shurufa.utils.Constants;
import me.shurufa.utils.RecyclerViewStateUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.LoadingFooter;
import me.shurufa.widget.recyclerview.HeaderAndFooterRecyclerViewAdapter;
import me.shurufa.widget.recyclerview.RecyclerViewUtils;

/**
 * 作者 : andy
 * 日期 : 16/5/16 10:31
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 书目录Fragment
 */
public class CatalogFragment extends BaseFragment implements View.OnClickListener {
    @Bind(R.id.recycler_view)
    SuperRecyclerView recyclerView;

    @Bind(R.id.ll_no_chapter)
    LinearLayout ll_no_chapter;

    @Bind(R.id.btn_tell_need_chapter)
    Button btn_tell_need_chapter;

    @Bind(R.id.fl_content)
    FrameLayout content;

    @Bind(R.id.progress)
    SpinKitView progressBar;

    private NewCatalogAdapter catalogAdapter;
    private ArrayList<Catalog> dataList;
    private HeaderAndFooterRecyclerViewAdapter mHeaderAndFooterRecyclerViewAdapter = null;

    private long bookId;
    private View headerView;

    private int mPage;
    private boolean hasMore = true;

    public static CatalogFragment newInstance(long bookId) {
        CatalogFragment fragment = new CatalogFragment();
        Bundle args = new Bundle();
        args.putLong(Constants.ARG_BOOK_ID, bookId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            bookId = getArguments().getLong(Constants.ARG_BOOK_ID);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_book_catalog, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        dataList = new ArrayList<>();
        catalogAdapter = new NewCatalogAdapter(getActivity(), dataList);
        mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(catalogAdapter);
        recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);
        recyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        initHeader();
        RecyclerViewUtils.setHeaderView(recyclerView.getRecyclerView(), headerView);
        //recyclerView.setOnScrollListener(mOnScrollListener);
        btn_tell_need_chapter.setOnClickListener(this);

        loadData();
    }

    private void initHeader() {
        headerView = LayoutInflater.from(getActivity()).inflate(R.layout.item_header_gray, recyclerView, false);
    }

    /*private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);

            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(recyclerView.getRecyclerView());
            if (state == LoadingFooter.State.Loading) {
                LogUtils.kLog().e("the state is Loading, just wait..");
                return;
            }

            if (hasMore) {
                // loading more
                RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), 15, LoadingFooter.State.Loading, null);
                loadData();
            } else {
                //the end
                RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), 15, LoadingFooter.State.TheEnd, null);
            }
        }
    };*/

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }


    /**
     * 加载数据
     *
     */
    private void loadData() {
        RequestParams params = new RequestParams();
        params.addFormDataPart("id", bookId);
        HttpRequest.post(API.GET_BOOK_MENU, params, new HttpCallback<CatalogListResp>() {
            @Override
            public void onRespSuccess(CatalogListResp resp) {
                try {
                    ArrayList<Catalog> catalogs = (ArrayList<Catalog>) resp.data;
                    //没有更多数据 不能加载更多
                    if (Utils.isNullForList(catalogs)) {
                        hasMore = false;
                        RecyclerViewStateUtils.setFooterViewState(recyclerView.getRecyclerView(), LoadingFooter.State.TheEnd);

                        if (Utils.isNullForList(dataList)) {
                            content.setVisibility(View.GONE);
                            ll_no_chapter.setVisibility(View.VISIBLE);
                        }
                    } else {
                        RecyclerViewStateUtils.setFooterViewState(recyclerView.getRecyclerView(), LoadingFooter.State.TheEnd);
                        hasMore = false;
                        catalogAdapter.append(resp.data);
                    }
                } catch (Exception e){
                }
            }

            @Override
            public void onRespFailure(CatalogListResp resp) {

            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
                content.setVisibility(View.GONE);
                ll_no_chapter.setVisibility(View.VISIBLE);
            }

            @Override
            public void onStart() {
                super.onStart();
                if (null != progressBar) {
                    progressBar.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (null != progressBar) {
                    progressBar.setVisibility(View.GONE);
                }
            }
        });
    }




    /*protected void loadData(final int page) {
        if (!NetworkUtils.isNetAvailable(getActivity())){
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, 10, LoadingFooter.State.NetWorkError, this.mFooterClick);
        }else {
            RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Loading);
            new RequestServerTask<CatalogListResponse>(CatalogListResponse.class) {
                @Override
                protected String requestServer() {
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("bookId", bookId);
                    params.put("page",page);
                    LogUtils.kLog().e("page="+page);
                    return HttpUtil.post(API.GET_BOOK_MENU, params);
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    try {
                        // loadingView.setVisibility(View.GONE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    try {
                        // loadingView.setVisibility(View.VISIBLE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                // ////////////////Notice！！ 目前目录是一次性全部加载 所以不算分页 加载成功后直接设置已全部加载
                @Override
                protected void onSuccess(CatalogListResponse result) {
                    //没有更多数据 不能加载更多
                    if (result.data == null || result.data.length == 0) {
                        hasMore = false;
                        RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.TheEnd);

                        if (Utils.isNullForList(dataList)) {
                            content.setVisibility(View.GONE);
                            ll_no_chapter.setVisibility(View.VISIBLE);
                        }
                    } else {
//                        RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Normal);
                        RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.TheEnd);
//                        hasMore = true;
                        hasMore = false;
                        mPage++;
                        bindData(result, page == 1);
                    }
                }
            }.start();
        }
    }*/


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_tell_need_chapter:
                //Utils.showToast("还没告诉呢");
                break;
        }
    }

    public RecyclerView findRecyclerView() {
        if (recyclerView != null) {
            return recyclerView.getRecyclerView();
        }
        return null;
    }
}
